#include "aes.h"
#include <openssl/aes.h>

#define KEY_SIZE_BITS 128
#define BLOCK_SIZE_BYTES 16
#define MIN_CHAR 32
#define MAX_CHAR 127

int validateBlock(unsigned char * s, int n);

int
decryptAES(FILE * encFile, FILE * result, unsigned char * key )
{
    int n;
    int validKey = 1;
    unsigned char blockIn[BLOCK_SIZE_BYTES], blockOut[BLOCK_SIZE_BYTES];
    unsigned char ivec[BLOCK_SIZE_BYTES] = {0};
    AES_KEY AES_format_key;
    int fileSize, blockNum;

	fseek(encFile, 0, SEEK_END);
	fileSize = ftell(encFile);
	fseek(encFile, 0, SEEK_SET);

	blockNum = fileSize / BLOCK_SIZE_BYTES;

    while( validKey && ! feof(encFile) )
    {
        n = fread(blockIn, 1, BLOCK_SIZE_BYTES, encFile);

        AES_set_decrypt_key(key, KEY_SIZE_BITS, &AES_format_key);
        AES_cbc_encrypt(blockIn, blockOut, n, &AES_format_key, ivec, 0);

        //El ultimo bloque tiene padding, asi que lo trato diferente
		if ( blockNum > 1)
		{
	        if (validateBlock(blockOut, n))
	        {
	            fwrite(blockOut, 1, n, result);
	        }
	        else
	        {
		       	rewind(encFile); //pongo los archivos en el comienzo
		    	rewind(result);
	            return 0;
	        }
		}
		else
		{
			int count = 0;
			while ( count < n && blockOut[count] >= MIN_CHAR 
				&& blockOut[count] <= MAX_CHAR)
				count++;
			fwrite(blockOut, 1, count, result);
		}

		blockNum--;
    }

    return 1;

}

int
validateBlock(unsigned char * s, int n)
{
    int i, result = 1;

    for( i = 0 ; i < n && result ; i++ )
	{
        if( s[i] < MIN_CHAR || s[i] > MAX_CHAR  )
            result = 0;
    }

    return result;
}
